import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import jwtDecode from "jwt-decode";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: Login,
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
    children: [ 
      {
        path: '/about',
        name: 'home',
        // meta:{"title":"用户列表"},
        component: () => import('../views/index/home.vue')
      },
      {
        path: '/users',
        name: 'users',
        // meta:{"title":"用户列表"},
        component: () => import('../views/index/users.vue')
      },
      {
        path: '/rights', 
        name: 'rights',
        // meta:{"title":"权限列表"},
        component: () => import('../views/index/rights.vue')
      },
      {
        path: '/roles',
        name: 'roles',
        // meta:{"title":"角色列表"},
        component: () => import('../views/index/roles.vue')
      }, 
      {
        path: '/orders', 
        name: 'orders',
        // meta:{"title":"订单列表"},
        component: () => import('../views/index/orders.vue')
      },
      {
        path: '/goods',
        name: 'goods',
        // meta:{"title":"商品列表"},
        component: () => import('../views/index/goods.vue')
      },
      {
        path: '/goods/add',
        name: 'goodsAdd',
        component: () => import('../views/index/goodsAdd.vue'),
        meta:{parentPach:"/goods"}
      },
      {
        path: '/params', 
        name: 'params',
        // meta:{"title":"商品参数"},
        component: () => import('../views/index/params.vue')
      },
      {
        path: '/categories', 
        name: 'categories',
        // meta:{"title":"商品分类"},
        component: () => import('../views/index/categories.vue')
      },
      {
        path: '/reports', 
        name: 'reports', 
        // meta:{"title":"数据报表"},
        component: () => import('../views/index/reports.vue')
      },
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, form, next) => {
  document.title=to.meta.title
  if (to.path === '/') {
    next()
  } 

  if (to.path !== '/') {
    let token = localStorage.getItem("token") 
    if (!token) {
      //  没有token
      next('/')
    } else {
      // 有token,判断是否过期  过期则失效
      let {exp,name}=jwtDecode(token)
      let nowtime=new Date().getTime();
      nowtime=Math.floor(nowtime/1000);
      if(exp-nowtime>=0){
        next()
      }else{
        next("/")
      }
     
    }
  }
})
 



export default router
